package org.lanplay.server;

import java.net.UnknownHostException;

import jcifs.netbios.NbtAddress;

import org.apache.wicket.Application;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.protocol.http.servlet.ServletWebRequest;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.cycle.RequestCycle;
import org.lanplay.server.dao.UserDao;
import org.lanplay.server.model.User;

import com.google.inject.Inject;

public class LanPlaySession extends AuthenticatedWebSession {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final String USER_ATTRIBUTE = LanPlaySession.class.getName()
			+ ".USER_ATTRIBUTE";

	@Inject
	private final UserDao userDao = null;

	public LanPlaySession(Request request) {
		super(request);
		LanPlayApplication application = (LanPlayApplication) Application.get();
		application.getInjector().getMembersInjector(LanPlaySession.class)
				.injectMembers(this);
		String key = getNetbiosName();
		User user = userDao.getByKey(key);
		if (user != null && user.getPassword() == null) {
			setAttribute(USER_ATTRIBUTE, user.getId());
			signIn(true);
		} else if (user == null) {
			user = application.createUserWithKey(key);
			setAttribute(USER_ATTRIBUTE, user.getId());
			signIn(true);
		}
	}

	@Override
	public boolean authenticate(String username, String password) {
		User user = userDao.getByName(username);
		if (user != null && password != null && password.length() != 0
				&& password.equals(user.getPassword())) {
			setAttribute(USER_ATTRIBUTE, user.getId());
			return true;
		}
		return false;
	}

	@Override
	public Roles getRoles() {
		if (getAttribute(USER_ATTRIBUTE) != null)
			return new Roles(Roles.USER);
		return new Roles();
	}

	private String getNetbiosName() {
		String remoteAddr = ((ServletWebRequest) RequestCycle.get()
				.getRequest()).getContainerRequest().getRemoteAddr();
		String hostName = remoteAddr;
		try {
			NbtAddress name = NbtAddress.getByName(remoteAddr);
			NbtAddress[] addresses = NbtAddress.getAllByAddress(name);
			if (addresses.length > 0) {
				hostName = addresses[0].getHostName();
			}
		} catch (UnknownHostException e) {
		}
		return hostName;
	}

}
